<script setup lang="ts">
import { reactive, onMounted, watch } from 'vue';
import { Right as AppNutIconRight } from '@nutui/icons-vue-taro';
import { eventCenter, getCurrentInstance } from '@tarojs/taro';
import { LOGIN_APP } from '/@/api/modules/base/app-sys-user';
const props = defineProps<{
  deptId?: string;
  /**
   * 部门名称
   */
  deptName?: string;
}>();
//初始化
watch(
  () => props.deptName,
  () => {
    state.deptId = props.deptId || '';
    state.deptName = props.deptName || '';
  },
);

const emits = defineEmits<{
  (e: 'onChange', deptId: string, deptName: string): void;
}>();
//局部
const state = reactive<{
  /**
   * 部门选择
   */
  departmentIsShow: boolean;
  deptId: string;
  deptName: string;
}>({
  departmentIsShow: false,
  deptId: '',
  deptName: '',
});

/**
 * 选择部门
 */
function selectDepartment(_organIds: string[], organs: AppCascaderOrganDto[]) {
  state.deptId = organs[organs.length - 1].value;
  state.deptName = organs[organs.length - 1].text;
  emits('onChange', state.deptId, state.deptName);
}
onMounted(() => {
  eventCenter.on(getCurrentInstance().router?.onShow as string, () => {
    //清理数据，当成功页面返回的时候，显示初始状态
    state.deptId = '';
    state.deptName = '';
    defaultDepartment();
  });
});

function defaultDepartment() {
  LOGIN_APP().then((res) => {
    if (res.organDtos && res.organDtos.length > 0) {
      const organ = res.organDtos[0];
      state.deptId = organ.id || '';
      state.deptName = organ.name || '';
      emits('onChange', state.deptId, state.deptName);
    }
  });
}
</script>
<template>
  <view
    class="item-type-select-department"
    @click="state.departmentIsShow = !state.departmentIsShow"
  >
    <text>{{ state.deptName || '请选择部门' }}</text>
    <app-nut-icon-right />
  </view>
  <app-organ-cascader
    title="选择部门"
    v-model="state.departmentIsShow"
    @on-selected="selectDepartment"
  />
</template>
<style lang="scss">
.item-type-select-department {
  display: flex;
  justify-content: flex-end;
  align-items: center;
}
</style>
